const { ipcRenderer,desktopCapturer  } = require('electron')
const systemInfo = require('systeminformation');
const osNode = require('os');
	
const logger = require('electron-log');
const fs = require('fs');
const ini = require('ini');
var isDev = false;
const shortuuid = require('short-uuid');
function loginfo(text) {
	//logger.info("html log:" + text);
}
function logwarn(text) {
	logger.warn("html log:" + text);
}
function logerror(text) {
	logger.error("html log:" + text);
}
var VisualConst = function () { }

var ____clientStaticData = {};
var ____clientDeviceInfo = {};//设备的注册信息
var ____clientDeviceId = "";
const node_Conf = require('conf');
const node_config = new node_Conf();
VisualConst.getAppCfg = function () {
	return node_config.get("runConfig");
}

VisualConst.getScreenSize = function () {
	const screenSize = {
		width:window.screen.width,
		height:window.screen.height
	};
	return screenSize
}
VisualConst.getScreenType = function () {
	const screenSize = {
		width:window.screen.width,
		height:window.screen.height
	};
	var s = 'h';
	if(screenSize.width > screenSize.height){
		s= 'h';
	}else{
		s= 'v';
	}
	return s;
}
function determineScreenShotSize() {
	const screenSize = VisualConst.getScreenSize();
	const maxDimension = Math.max(screenSize.width, screenSize.height)
	return {
		width: maxDimension * window.devicePixelRatio,
		height: maxDimension * window.devicePixelRatio
	}
}

// var config = {};
try {
	// config = VisualConst.getAppCfg();
	isDev = VisualConst.getAppCfg()["isDev"];
} catch (error) {
	console.log(error);
}

loginfo(navigator.userAgent.toLowerCase());


VisualConst.getDeviceNetwork = function() {
	var interfaces = osNode.networkInterfaces();
	for (var devName in interfaces) {
		var iface = interfaces[devName];
		for (var i = 0; i < iface.length; i++) {
			var alias = iface[i];
			if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
				return alias;
			}
		}
	}
}
VisualConst.getCustomDevice = function (system) {
	//先读取页面缓存，再读取本地存储的 deviceid
	if ("" == ____clientDeviceId || null == ____clientDeviceId) {
		var fileDir = process.env.USERPROFILE + "/AppData/Roaming/chudy-visual/";
		//读取本地
		var file = fileDir + "clientinfo.chudy";
		try {
			fs.accessSync(file, fs.constants.F_OK);
			loginfo('可以读写');
			//文件存在则读取
			var customconfig = ini.parse(fs.readFileSync(file, 'utf-8'));
			//console.log(customconfig);

			____clientDeviceId = customconfig["clientreg"]["deviceid"];
			loginfo("正在读取设备id" + ____clientDeviceId);
		} catch (err) {
			fs.mkdirSync(fileDir, { recursive: true });
			//文件不存在
            var tempdeviceid = shortuuid.generate();
            var config = {};
            config["clientreg"] = {
                "deviceid": tempdeviceid
			};
			console.log("正在创建设备id" + tempdeviceid);
			fs.writeFileSync(file, ini.stringify(config));
			____clientDeviceId = tempdeviceid;
		}
	}

	return { "deviceid": ____clientDeviceId, "displaysize": VisualConst.getScreenSize() };
}

VisualConst.getMemory = function (cb) {
	//获得设备的mac地址，并且写入到本地，作为设备的id
	systemInfo.mem(function (data) {
		cb(data);
	})
}

VisualConst.getDynamicData = function (cb) {
    //获得设备的mac地址，并且写入到本地，作为设备的id
    systemInfo.getDynamicData("","",function (data) {
        var dataF = {};
        var filter = ["time","mem","users","battery","fsSize"];
		for (var i = 0; i < filter.length; i++) {
			dataF[filter[i]] = data[filter[i]];
		}
        cb(dataF);
    })
}


VisualConst.getClientStaticData = function (cb) {
	if (JSON.stringify(____clientStaticData) != "{}") {
		cb(____clientStaticData);
	} else {

		let osInfo = {};
		osInfo["arch"] = osNode.arch();
		osInfo["hostname"] = osNode.hostname();
		// osInfo["cpus"] = osNode.cpus();
		osInfo["platform"] = osNode.platform();
		osInfo["release"] = osNode.release();
		osInfo["type"] = osNode.type();
		osInfo["uptime"] = osNode.uptime();
		osInfo["version"] = osNode.version();
		osInfo["freemem"] = osNode.freemem();
		osInfo["totalmem"] = osNode.totalmem();
		var data = {
			"os":osInfo,
			"network":VisualConst.getDeviceNetwork()
		};
		data["_customDevice"] = VisualConst.getCustomDevice();
		____clientStaticData = data;
		cb(data);
	}
}





function clientDesktopCapturer(options, cb) {
	const thumbSize = determineScreenShotSize()
	let cfg = { types: ['screen'], thumbnailSize: thumbSize }

	desktopCapturer.getSources(cfg, function (error, sources) {
		if (error) return console.log(error)
		var isCb = false;
		sources.forEach(function (source) {
			if (source.name === 'Entire screen' || source.name === 'Screen 1') {
				//console.log(source.thumbnail.toDataURL())
				isCb = true;
				cb(source.thumbnail.resize({ width: thumbSize.width / 2 }).toDataURL());
				/*
				const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
				fs.writeFile(screenshotPath, source.thumbnail.toPng(), function (error) {
					if (error) return console.log(error)
					shell.openExternal('file://' + screenshotPath)
					const message = `截图保存到: ${screenshotPath}`
					screenshotMsg.textContent = message
				})
				*/
			}
		})
		if (!isCb) {
			cb(null);
		}
	})
}

VisualConst.appendDeviceParam = function (url) {
	if(!url)
		return url;
	var locationId = "";
	var _clientid = "";
	var _clientip = "";
	if(____clientDeviceInfo){
		locationId = ____clientDeviceInfo["locationId"] ||"";
		_clientid = (____clientDeviceInfo["id"]||"");
		_clientip = (____clientDeviceInfo["ip"]||"");
	}
	
	url = url.replace("$locationId$",locationId);
	url = url.replace("$_clientid$",_clientid);
	url = url.replace("$_clientip$",_clientip);
	if(url.indexOf("?")>0){
		url = url + "&_locationId=" + locationId + "&_clientip=" + _clientip + "&_clientid=" + _clientid ;
	}else{
		url = url + "?_locationId=" + locationId + "&_clientip=" + _clientip + "&_clientid=" + _clientid ;
	}
	//console.log("____clientDeviceInfo",____clientDeviceInfo,url);
	return url;
}

VisualConst.____renderSysinfo = function (staticdata) {
	var sysinfo = "<table>";
	const { width, height } = VisualConst.getScreenSize();
	sysinfo += "<tr><td>screen</td><td>" + width + "x" + height + "</td></tr>";
	for (var key in staticdata["system"]) {
		sysinfo += "<tr><td>" + key + "</td><td>" + staticdata["system"][key] + "</td></tr>";
	}
	sysinfo += "</table>";
	return sysinfo;
}

VisualConst.getServerInfo = function (){
	return Lib.getStorage('serverInfo') || {};
}
VisualConst.setServerInfo = function (info){
	Lib.setStorage('serverInfo',info);
}

VisualConst.getLastContent = function (){
	return Lib.getStorage('lastList') || {};
}
VisualConst.setLastContent = function (list){
	Lib.setStorage('lastList',list);
}